function insertHtmlAfter(targetElement, htmlString) {
    // 创建临时容器来解析HTML字符串
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = htmlString;
    
    // 获取所有解析后的子节点
    const nodes = Array.from(tempDiv.childNodes);
    
    // 依次将每个节点插入到目标元素之后
    let currentNode = targetElement;
    nodes.forEach(node => {
        const parent = currentNode.parentNode;
        const nextSibling = currentNode.nextSibling;
        parent.insertBefore(node, nextSibling);
        currentNode = node; // 更新当前节点为最新插入的节点
    });
}

// 当前滚动下标
let scrollIndex = 0;
// 计算可滚动次数
let scrollTimes = 0;

// 商品图片滚动事件
function scrollImages(direction) {
    // 获取滚动容器
    const scrollDom = document.getElementById('img-scroll');
    if(direction === 'left'){
        scrollIndex -= 1;
        if(scrollIndex < 0){
            scrollIndex = 0;
            return;
        }
        scrollDom.style.transform = `translateX(${scrollIndex * (-100)}%)`;
    }else if(direction === 'right'){
        scrollIndex += 1;
        if(scrollIndex >= scrollTimes){
            scrollIndex = scrollTimes - 1;
            return;
        }
        scrollDom.style.transform = 'translateX(-'+(scrollIndex*100 + 5)+'%)';
    }
}

// 当前展示图片下标
let currentImgIndex = 0; 

function changeImg(index, src) {
    if(index === currentImgIndex)return;
    const imgDom = document.querySelector('.current-img');
    imgDom.src = src;
    currentImgIndex = index;
}

onload = () => {
    // 左侧图片滚动逻辑
    
    // 获取滚动容器
    const scrollDom = document.getElementById('img-scroll');

    // 获取滚动容器下有几个子元素
    const childrenCount = scrollDom.children.length;

    // 计算可滚动次数
    scrollTimes = Math.ceil(childrenCount / 3);

    // 图片列表绑定点击事件
    for (let i = 0; i < childrenCount; i++) {
        scrollDom.children[i].addEventListener('click', function() {
            changeImg(i, this.src)
        })
    }


    // 右侧精选推荐列表
    const target = document.getElementById('right-list');
    let htmlStr = '';
    for (let i = 0; i < 10; i++) {
        const element = `
        <div class="product-item">
            <img src="./imgs/list1.png  " alt="金色iPhone" class="product-image">
            <div class="product-info">
                <div class="product-name">临汾二手新能源汽车电池包 埃安Y电池包回收出售宁德174ah</div>
                <div class="product-price">¥8,499</div>
            </div>
        </div>
        `
        htmlStr += element;
    }
    insertHtmlAfter(target, htmlStr);

}